// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Page heap.
//
// See malloc.h for overview.
//
// When a MSpan is in the heap free list, state == MSpanFree
// and heapmap(s->start) == span, heapmap(s->start+s->npages-1) == span.
//
// When a MSpan is allocated, state == MSpanInUse
// and heapmap(i) == span for all s->start <= i < s->start+s->npages.

#include <align.h>
#include <as.h>

#include "runtime_types.h"
#include "lock.h"
#include "util.h"
#include "panic.h"
#include "print.h"

#include "mem_size.h"
#include "mem_stats.h"
#include "mem_fixalloc.h"
#include "mem_sys.h"
#include "mem_heap.h"

static MSpan *MHeap_AllocLocked(MHeap*, uintptr, int32);
static bool MHeap_Grow(MHeap*, uintptr);
static void MHeap_FreeLocked(MHeap*, MSpan*);
static MSpan *MHeap_AllocLarge(MHeap*, uintptr);
static MSpan *BestFit(MSpan*, uintptr, MSpan*);

enum {
	PageShift = PAGE_WIDTH,
};

struct MHeap runtime_mheap;

static void
RecordSpan(void *vh, byte *p)
{
	// Just adds a newly allocated span into the list of all spans.
	MHeap *h;
	MSpan *s;

	h = vh;
	s = (MSpan*)p;
	s->allnext = h->allspans;
	h->allspans = s;
}

// Initialize the heap.
void
runtime_MHeap_Init(MHeap *h)
{
	uint32 i;

	runtime_FixAlloc_Init(&h->spanalloc, sizeof(MSpan), runtime_sys_alloc, RecordSpan, h);

	for(i=0; i<nelem(h->free); i++)
		runtime_MSpanList_Init(&h->free[i]);
	runtime_MSpanList_Init(&h->large);

	bool done = false;
	uintptr arena_size, bitmap_size;

	// Set up the allocation arena, a contiguous area of memory where
	// allocated data will be found.  The arena begins with a bitmap large
	// enough to hold 4 bits per allocated word.
	if(sizeof(void*) == 8) {
		// On a 64-bit machine, allocate from a single contiguous reservation.
		// 16 GB should be big enough for now.
		//
		// The code will work with the reservation at any address, but ask
		// SysReserve to use 0x000000f800000000 if possible.
		// Allocating a 16 GB region takes away 36 bits, and the amd64
		// doesn't let us choose the top 17 bits, so that leaves the 11 bits
		// in the middle of 0x00f8 for us to choose.  Choosing 0x00f8 means
		// that the valid memory addresses will begin 0x00f8, 0x00f9, 0x00fa, 0x00fb.
		// None of the bytes f8 f9 fa fb can appear in valid UTF-8, and
		// they are otherwise as far from ff (likely a common byte) as possible.
		// Choosing 0x00 for the leading 6 bits was more arbitrary, but it
		// is not a common ASCII code point either.  Using 0x11f8 instead
		// caused out of memory errors on OS X during thread allocations.
		// These choices are both for debuggability and to reduce the
		// odds of the conservative garbage collector not collecting memory
		// because some non-pointer block of memory had a bit pattern
		// that matched a memory address.
		//
		// Actually we reserve 17 GB (because the bitmap ends up being 1 GB)
		// but it hardly matters: fc is not valid UTF-8 either, and we have to
		// allocate 15 GB before we get that far.
		//
		// If this fails we fall back to the 32 bit memory mechanism
		arena_size = (uintptr)(16LL<<30);
		bitmap_size = arena_size / WordsPerBitmapWord;

		done = runtime_sys_create(&h->arena, (0x00f8ULL<<32) / PAGE_SIZE, (bitmap_size + arena_size) / PAGE_SIZE);
	}

	if (!done) {
		// On a 32-bit machine, we can't typically get away
		// with a giant virtual address space reservation.
		// Instead we map the memory information bitmap
		// immediately after the data segment, large enough
		// to handle another 2GB of mappings (256 MB),
		// along with a reservation for another 512 MB of memory.
		// When that gets used up, we'll start asking the kernel
		// for any memory anywhere and hope it's in the 2GB
		// following the bitmap (presumably the executable begins
		// near the bottom of memory, so we'll have to use up
		// most of memory before the kernel resorts to giving out
		// memory before the beginning of the text segment).
		//
		// Alternatively we could reserve 512 MB bitmap, enough
		// for 4GB of mappings, and then accept any memory the
		// kernel threw at us, but normally that's a waste of 512 MB
		// of address space, which is probably too much in a 32-bit world.
		arena_size = 512<<20;
		bitmap_size = MaxArena32 / WordsPerBitmapWord;

		done = runtime_sys_create(&h->arena, 0, (bitmap_size + arena_size) / PAGE_SIZE);
		if (!done) {
			runtime_throw("runtime: cannot reserve arena virtual address space");
		}
	}

	h->bitmap = runtime_sys_page_addr(&h->arena, 0);
	h->arena_start = runtime_sys_page_addr(&h->arena, bitmap_size / PAGE_SIZE);
	h->arena_used = h->arena_start;
	h->arena_end = h->arena_start + arena_size;
}

// Allocate a new span of npage pages from the heap
// and record its size class in the HeapMap and HeapMapCache.
MSpan*
runtime_MHeap_Alloc(MHeap *h, uintptr npage, int32 sizeclass, int32 acct)
{
	MSpan *s;

	runtime_lock(h);
	runtime_purgecachedstats();
	s = MHeap_AllocLocked(h, npage, sizeclass);
	if(s != nil) {
		mstats.heap_inuse += npage<<PageShift;
		if(acct) {
			mstats.heap_objects++;
			mstats.heap_alloc += npage<<PageShift;
		}
	}
	runtime_unlock(h);
	return s;
}

static MSpan*
MHeap_AllocLocked(MHeap *h, uintptr npage, int32 sizeclass)
{
	uintptr n;
	MSpan *s, *t;
	PageID p;

	// Try in fixed-size lists up to max.
	for(n=npage; n < nelem(h->free); n++) {
		if(!runtime_MSpanList_IsEmpty(&h->free[n])) {
			s = h->free[n].next;
			goto HaveSpan;
		}
	}

	// Best fit in list of large spans.
	if((s = MHeap_AllocLarge(h, npage)) == nil) {
		if(!MHeap_Grow(h, npage))
			return nil;
		if((s = MHeap_AllocLarge(h, npage)) == nil)
			return nil;
	}

HaveSpan:
	// Mark span in use.
	if(s->state != MSpanFree)
		runtime_throw("MHeap_AllocLocked - MSpan not free");
	if(s->npages < npage)
		runtime_throw("MHeap_AllocLocked - bad npages");
	runtime_MSpanList_Remove(s);
	s->state = MSpanInUse;
	mstats.heap_idle -= s->npages<<PageShift;
	mstats.heap_released -= s->npreleased<<PageShift;
	s->npreleased = 0;

	if(s->npages > npage) {
		// Trim extra and put it back in the heap.
		t = runtime_FixAlloc_Alloc(&h->spanalloc);
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
		runtime_MSpan_Init(t, s->start + npage, s->npages - npage);
		s->npages = npage;
		p = t->start;
		if(sizeof(void*) == 8)
			p -= ((uintptr)h->arena_start>>PageShift);
		if(p > 0)
			h->map[p-1] = s;
		h->map[p] = t;
		h->map[p+t->npages-1] = t;
		*(uintptr*)(t->start<<PageShift) = *(uintptr*)(s->start<<PageShift);  // copy "needs zeroing" mark
		t->state = MSpanInUse;
		MHeap_FreeLocked(h, t);
	}

	if(*(uintptr*)(s->start<<PageShift) != 0)
		runtime_memclr((byte*)(s->start<<PageShift), s->npages<<PageShift);

	// Record span info, because gc needs to be
	// able to map interior pointer to containing span.
	s->sizeclass = sizeclass;
	p = s->start;
	if(sizeof(void*) == 8)
		p -= ((uintptr)h->arena_start>>PageShift);
	for(n=0; n<npage; n++)
		h->map[p+n] = s;
	return s;
}

// Allocate a span of exactly npage pages from the list of large spans.
static MSpan*
MHeap_AllocLarge(MHeap *h, uintptr npage)
{
	return BestFit(&h->large, npage, nil);
}

// Search list for smallest span with >= npage pages.
// If there are multiple smallest spans, take the one
// with the earliest starting address.
static MSpan*
BestFit(MSpan *list, uintptr npage, MSpan *best)
{
	MSpan *s;

	for(s=list->next; s != list; s=s->next) {
		if(s->npages < npage)
			continue;
		if(best == nil
		|| s->npages < best->npages
		|| (s->npages == best->npages && s->start < best->start))
			best = s;
	}
	return best;
}

// Try to add at least npage pages of memory to the heap,
// returning whether it worked.
static bool
MHeap_Grow(MHeap *h, uintptr npage)
{
	uintptr ask;
	void *v;
	MSpan *s;
	PageID p;

	// Ask for a big chunk, to reduce the number of mappings
	// the operating system needs to track; also amortizes
	// the overhead of an operating system mapping.
	// Allocate a multiple of 64kB (16 pages).
	npage = (npage+15)&~15;
	ask = npage<<PageShift;
	if(ask < HeapAllocChunk)
		ask = HeapAllocChunk;

	v = runtime_MHeap_SysAlloc(h, ask);
	if(v == nil) {
		if(ask > (npage<<PageShift)) {
			ask = npage<<PageShift;
			v = runtime_MHeap_SysAlloc(h, ask);
		}
		if(v == nil) {
			runtime_printf("runtime: out of memory: cannot allocate %D-byte block (%D in use)\n", (uint64)ask, mstats.heap_sys);
			return false;
		}
	}
	mstats.heap_sys += ask;

	// Create a fake "in use" span and free it, so that the
	// right coalescing happens.
	s = runtime_FixAlloc_Alloc(&h->spanalloc);
	mstats.mspan_inuse = h->spanalloc.inuse;
	mstats.mspan_sys = h->spanalloc.sys;
	runtime_MSpan_Init(s, (uintptr)v>>PageShift, ask>>PageShift);
	p = s->start;
	if(sizeof(void*) == 8)
		p -= ((uintptr)h->arena_start>>PageShift);
	h->map[p] = s;
	h->map[p + s->npages - 1] = s;
	s->state = MSpanInUse;
	MHeap_FreeLocked(h, s);
	return true;
}

static bool
runtime_MHeap_MapBits(MHeap *h)
{
	// Caller has added extra mappings to the arena.
	// Add extra mappings of bitmap words as needed.
	uintptr n;

	n = (h->arena_used - h->arena_start) / WordsPerBitmapWord;
	n = ALIGN_UP(n, PAGE_SIZE);

	if (h->bitmap_mapped >= n)
		return true;

	if (!runtime_sys_contains(&h->arena, h->arena_start - n)) {
		runtime_throw("Invalid arena in runtime_MHeap_MapBits() (BUG).\n");
	}

	uintptr start = runtime_sys_page_id(&h->arena, h->arena_start - n);
	if (!runtime_sys_claim(&h->arena, start, (n - h->bitmap_mapped) / PAGE_SIZE)) {
		return false;
	}
	h->bitmap_mapped = n;
	return true;
}

void*
runtime_MHeap_SysAlloc(MHeap *h, uintptr n)
{
	if(sizeof(void*) == 4 && n > (uintptr)(h->arena_end - h->arena_used)) {
		// If using 32-bit, maybe we didn't use all possible address space yet.
		// Reserve some more space.
		uintptr needed;
		uintptr new_pages;

		needed = (uintptr)h->arena_used + n - (uintptr)h->arena_end;
		// Round wanted arena size to a multiple of 256MB.
		needed = ALIGN_UP(needed, ArenaSizeMultiple);
		new_pages = runtime_sys_pages(&h->arena) + (needed / PAGE_SIZE);

		if (new_pages <= (MaxArena32 / PAGE_SIZE) && runtime_sys_resize(&h->arena, new_pages)) {
			h->arena_end += needed;
		}
	}

	if(n <= (uintptr)(h->arena_end - h->arena_used)) {
		// Keep taking from our reservation.
		void *allocation = h->arena_used;
		PageID p = runtime_sys_page_id(&h->arena, allocation);
		uintptr pages = n / PAGE_SIZE;
		if (!runtime_sys_claim(&h->arena, p, pages)) {
			return nil;
		}
		h->arena_used += n;
		if (!runtime_MHeap_MapBits(h)) {
			h->arena_used -= n;
			runtime_sys_release(&h->arena, p, pages);
			return nil;
		}
		return allocation;
	}

	// If using 64-bit, our reservation is all we have.
	if(sizeof(void*) == 8)
		return nil;

	// On 32-bit, once the reservation is gone we can
	// try to get memory at a location chosen by the OS
	// and hope that it is in the range we allocated bitmap for.
	byte *p = runtime_sys_alloc(n);
	if(p == nil)
		return nil;

	if(p < h->arena_start || (uintptr)(p+n - h->arena_start) >= MaxArena32) {
		runtime_printf("runtime: memory allocated by OS (%p) not in usable range [%p,%p)\n",
			p, h->arena_start, h->arena_start+MaxArena32);
		runtime_sys_free(p);
		return nil;
	}

	if(p+n > h->arena_used) {
		byte *used = h->arena_used;
		byte *end = h->arena_end;

		h->arena_used = p+n;
		if (h->arena_used > h->arena_end) {
			h->arena_end = h->arena_used;
		}

		if (!runtime_MHeap_MapBits(h)) {
			h->arena_used = used;
			h->arena_end = end;
			runtime_sys_free(p);
			return nil;
		}
	}

	return p;
}

// Look up the span at the given address.
// Address is guaranteed to be in map
// and is guaranteed to be start or end of span.
MSpan*
runtime_MHeap_Lookup(MHeap *h, void *v)
{
	uintptr p;

	p = (uintptr)v;
	if(sizeof(void*) == 8)
		p -= (uintptr)h->arena_start;
	return h->map[p >> PageShift];
}

// Look up the span at the given address.
// Address is *not* guaranteed to be in map
// and may be anywhere in the span.
// Map entries for the middle of a span are only
// valid for allocated spans.  Free spans may have
// other garbage in their middles, so we have to
// check for that.
MSpan*
runtime_MHeap_LookupMaybe(MHeap *h, void *v)
{
	MSpan *s;
	PageID p, q;

	if((byte*)v < h->arena_start || (byte*)v >= h->arena_used)
		return nil;
	p = (uintptr)v>>PageShift;
	q = p;
	if(sizeof(void*) == 8)
		q -= (uintptr)h->arena_start >> PageShift;
	s = h->map[q];
	if(s == nil || p < s->start || p - s->start >= s->npages)
		return nil;
	if(s->state != MSpanInUse)
		return nil;
	return s;
}

// Free the span back into the heap.
void
runtime_MHeap_Free(MHeap *h, MSpan *s, int32 acct)
{
	runtime_lock(h);
	runtime_purgecachedstats();
	mstats.heap_inuse -= s->npages<<PageShift;
	if(acct) {
		mstats.heap_alloc -= s->npages<<PageShift;
		mstats.heap_objects--;
	}
	MHeap_FreeLocked(h, s);
	runtime_unlock(h);
}

static void
MHeap_FreeLocked(MHeap *h, MSpan *s)
{
	uintptr *sp, *tp;
	MSpan *t;
	PageID p;

	if(s->state != MSpanInUse || s->ref != 0) {
		runtime_printf("MHeap_FreeLocked - span %p ptr %p state %d ref %d\n", s, s->start<<PageShift, s->state, s->ref);
		runtime_throw("MHeap_FreeLocked - invalid free");
	}
	mstats.heap_idle += s->npages<<PageShift;
	s->state = MSpanFree;
	s->unusedsince = 0;
	s->npreleased = 0;
	runtime_MSpanList_Remove(s);
	sp = (uintptr*)(s->start<<PageShift);

	// Coalesce with earlier, later spans.
	p = s->start;
	if(sizeof(void*) == 8)
		p -= (uintptr)h->arena_start >> PageShift;
	if(p > 0 && (t = h->map[p-1]) != nil && t->state != MSpanInUse) {
		tp = (uintptr*)(t->start<<PageShift);
		*tp |= *sp;	// propagate "needs zeroing" mark
		s->start = t->start;
		s->npages += t->npages;
		s->npreleased = t->npreleased; // absorb released pages
		p -= t->npages;
		h->map[p] = s;
		runtime_MSpanList_Remove(t);
		t->state = MSpanDead;
		runtime_FixAlloc_Free(&h->spanalloc, t);
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
	}
	if(p+s->npages < nelem(h->map) && (t = h->map[p+s->npages]) != nil && t->state != MSpanInUse) {
		tp = (uintptr*)(t->start<<PageShift);
		*sp |= *tp;	// propagate "needs zeroing" mark
		s->npages += t->npages;
		s->npreleased += t->npreleased;
		h->map[p + s->npages - 1] = s;
		runtime_MSpanList_Remove(t);
		t->state = MSpanDead;
		runtime_FixAlloc_Free(&h->spanalloc, t);
		mstats.mspan_inuse = h->spanalloc.inuse;
		mstats.mspan_sys = h->spanalloc.sys;
	}

	// Insert s into appropriate list.
	if(s->npages < nelem(h->free))
		runtime_MSpanList_Insert(&h->free[s->npages], s);
	else
		runtime_MSpanList_Insert(&h->large, s);
}

// Initialize a new span with the given start and npages.
void
runtime_MSpan_Init(MSpan *span, PageID start, uintptr npages)
{
	span->next = nil;
	span->prev = nil;
	span->start = start;
	span->npages = npages;
	span->freelist = nil;
	span->ref = 0;
	span->sizeclass = 0;
	span->state = 0;
	span->unusedsince = 0;
	span->npreleased = 0;
}

// Initialize an empty doubly-linked list.
void
runtime_MSpanList_Init(MSpan *list)
{
	list->state = MSpanListHead;
	list->next = list;
	list->prev = list;
}

void
runtime_MSpanList_Remove(MSpan *span)
{
	if(span->prev == nil && span->next == nil)
		return;
	span->prev->next = span->next;
	span->next->prev = span->prev;
	span->prev = nil;
	span->next = nil;
}

bool
runtime_MSpanList_IsEmpty(MSpan *list)
{
	return list->next == list;
}

void
runtime_MSpanList_Insert(MSpan *list, MSpan *span)
{
	if(span->next != nil || span->prev != nil) {
		runtime_printf("failed MSpanList_Insert %p %p %p\n", span, span->next, span->prev);
		runtime_throw("MSpanList_Insert");
	}
	span->next = list->next;
	span->prev = list;
	span->next->prev = span;
	span->prev->next = span;
}

// mark the span of memory at v as having n blocks of the given size.
// if leftover is true, there is left over space at the end of the span.
void
runtime_markspan(MHeap *h, void *v, uintptr size, uintptr n, bool leftover)
{
	MBits b;

	if((byte*)v+size*n > h->arena_used || (byte*)v < h->arena_start)
		runtime_throw("markspan: bad pointer");

	if(leftover)	// mark a boundary just past end of last block too
		n++;

	for (byte *p = v; n-- > 0; p += size) {
		// Okay to use non-atomic ops here, because we control
		// the entire span, and each bitmap word has bits for only
		// one span, so no other goroutines are changing these
		// bitmap words.
		
		runtime_bits_init(&b, h, p);
		runtime_bits_assign(&b, bitBlockBoundary, false);
	}
}

// unmark the span of memory at v of length n bytes.
void
runtime_unmarkspan(MHeap *h, void *v, uintptr n)
{
	uintptr *p, *b, off;

	byte *start = h->arena_start;
	byte *used = h->arena_used;

	if((byte*)v+n > used || (byte*)v < start)
		runtime_throw("markspan: bad pointer");

	p = v;
	off = p - (uintptr*)start;  // word offset
	if(off % WordsPerBitmapWord != 0)
		runtime_throw("markspan: unaligned pointer");
	b = (uintptr*)start - off/WordsPerBitmapWord - 1;
	n /= sizeof(void *);
	if(n%WordsPerBitmapWord != 0)
		runtime_throw("unmarkspan: unaligned length");
	// Okay to use non-atomic ops here, because we control
	// the entire span, and each bitmap word has bits for only
	// one span, so no other goroutines are changing these
	// bitmap words.
	n /= WordsPerBitmapWord;
	while(n-- > 0)
		*b-- = 0;
}

// mark the block at v of size n as allocated.
// If noptr is true, mark it as having no pointers.
void
runtime_markallocated(MHeap *h, void *v, uintptr n, bool noptr, bool atomic)
{
	if(0)
		runtime_printf("markallocated %p+%p\n", v, n);

	if((byte*)v+n > (byte*)h->arena_used || (byte*)v < h->arena_start)
		runtime_throw("markallocated: bad pointer");

	MBits bits;
	runtime_bits_init(&bits, h, v);
	uintptr new_bits = bitAllocated | (noptr ? bitNoPointers : 0);

	runtime_bits_assign(&bits, new_bits, atomic);
}

// mark the block at v of size n as freed.
void
runtime_markfreed(MHeap *h, void *v, uintptr n, bool atomic)
{
	if(0)
		runtime_printf("markallocated %p+%p\n", v, n);

	if((byte*)v+n > (byte*)h->arena_used || (byte*)v < h->arena_start)
		runtime_throw("markallocated: bad pointer");

	MBits bits;
	runtime_bits_init(&bits, h, v);
	runtime_bits_assign(&bits, bitBlockBoundary, atomic);
}

// check that the block at v of size n is marked freed.
void
runtime_checkfreed(MHeap *h, void *v, uintptr n)
{
	if(!runtime_checking)
		return;

	if((byte*)v+n > (byte*)h->arena_used || (byte*)v < h->arena_start)
		return;	// not allocated, so okay

	MBits bits;
	runtime_bits_init(&bits, h, v);
	if (runtime_bits_read(&bits, bitAllocated)) {
		runtime_printf("checkfreed %p+%lld\n", v, (long long)n);
		runtime_throw("checkfreed: not freed");
	}
}

// Lookup a span in which an object resides.
int32
runtime_mlookup(MHeap *h, void *v, byte **base, uintptr *size, MSpan **sp)
{
	uintptr n, i;
	byte *p;
	MSpan *s;

	s = runtime_MHeap_LookupMaybe(h, v);
	if(sp)
		*sp = s;
	if(s == nil) {
		runtime_checkfreed(h, v, 1);
		if(base)
			*base = nil;
		if(size)
			*size = 0;
		return 0;
	}

	p = (byte*)((uintptr)s->start * PAGE_SIZE);
	if(s->sizeclass == 0) {
		// Large object.
		if(base)
			*base = p;
		if(size)
			*size = s->npages * PAGE_SIZE;
		return 1;
	}

	if((byte*)v >= (byte*)s->limit) {
		// pointers past the last block do not count as pointers.
		return 0;
	}

	n = runtime_class_to_size[s->sizeclass];
	if(base) {
		i = ((byte*)v - p)/n;
		*base = p + i*n;
	}
	if(size)
		*size = n;

	return 1;
}
